package com.first.run.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.first.run.entity.SysPermission;
import com.first.run.entity.SysRole;
import com.first.run.entity.SysUser;
import com.first.run.mapper.SysUserMapper;
import com.first.run.service.SysPermissionService;
import com.first.run.service.SysRoleService;
import com.first.run.service.SysUserService;
import com.first.run.vo.UserInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private SysRoleService roleService;
    private SysPermissionService permissionService;

    @Override
    public SysUser findSysUserByUserName(String username) {
        return baseMapper.findSysUserByUserName(username);
    }

    @Override
    public UserInfo getUserInfo(SysUser sysUser) {
        UserInfo userInfo = new UserInfo();
        userInfo.setSysUser(sysUser);
        //设置角色列表  （ID）
        List<Integer> roleIds = roleService.findRolesByUserId(sysUser.getUserId())
                .stream()
                .map(SysRole::getRoleId)
                .collect(Collectors.toList());

        userInfo.setRoles(ArrayUtil.toArray(roleIds, Integer.class));

        //设置权限列表（menu.permission）
        Set<String> permissions = new HashSet<>();
        if (ArrayUtil.isNotEmpty(ArrayUtil.toArray(roleIds, Integer.class))) {
            //设置权限列表（menu.permission）
            roleIds.forEach(roleId -> {
                List<String> permissionList = permissionService.listPermissionByRoleId(roleId)
                        .stream()
                        .filter(permission -> StringUtils.isNotEmpty(permission.getPermission()))
                        .map(SysPermission::getPermission)
                        .collect(Collectors.toList());
                permissions.addAll(permissionList);
            });
        }
        userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
        return userInfo;
    }
}
